using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using UnityEngine;
using UnityEngine.Networking;
using Voodoo.Sauce.Internal.CrossPromo.Canvas;
using Voodoo.Sauce.Internal.CrossPromo.Models;
using Voodoo.Sauce.Internal.CrossPromo.Utils;
using Voodoo.Sauce.Internal.GDPR;

namespace Voodoo.Sauce.Internal.CrossPromo.RestClient
{
	internal class UnityRestClient : MonoBehaviour, IRestClient
	{
		private bool _retreiveInfo;

		private int _retries;

		private CoroutineQueue _queueDownload;

		private const string os = "android";

		internal static IRestClient CreateGameObject()
		{
			GameObject gameObject = new GameObject("RestClientCrossPromotion");
			return gameObject.AddComponent<UnityRestClient>();
		}

		private void Awake()
		{
			_retreiveInfo = false;
			_retries = 1;
			_queueDownload = new CoroutineQueue(this);
			UnityEngine.Object.DontDestroyOnLoad(base.gameObject);
		}

		public void GetGameInfoAndDownload()
		{
			VoodooCrossPromo.Info.CrossPromoIsReady = false;
			StartCoroutine(StartGetGameInfoAndDownload());
		}

		public void BufferVideosInCache()
		{
			_queueDownload.EnqueueAction(DownloadNextFiles(VoodooCrossPromo.Info.Waterfall.Count));
		}

		public bool IsRetrieveInfo()
		{
			return _retreiveInfo;
		}

		private IEnumerator StartGetGameInfoAndDownload()
		{
			_retreiveInfo = true;
			yield return StartGetGameInfo();
			yield return DownloadFiles();
			_retreiveInfo = false;
		}

		private IEnumerator StartGetGameInfo()
		{
			string url = string.Format("{0}/sdk/game/?bundleId={1}&cpFormat={2}&osType={3}&voodooSauceVersion={4}&filesInCache={5}&adId={6}", "https://crosspromo.voodoo.io/api", Application.identifier, VoodooCrossPromo.Info.Format, "android", "3.4.0b4", SerializerUtils.VideosFromCache(), (!VoodooGDPR.HasAdsConsent()) ? "00000000-0000-0000-0000-000000000000" : VoodooGDPR.GetIDFA());
			UnityWebRequest www = UnityWebRequest.Get(url);
			www.timeout = 10;
			www.SetRequestHeader("Authorization", "Token 16aaae9ea829470dc2993d0afe865d1165230589");
			yield return www.SendWebRequest();
			if (www.isNetworkError || www.isHttpError)
			{
				VoodooCrossPromo.Info.HasInternet = !www.isNetworkError;
				VoodooLog.Log(VoodooCrossPromo.TAG, $"Failed to retrieve game information for cross promotion {www.responseCode} {www.error}");
				if (www.responseCode != 404)
				{
					StartCoroutine(Retry());
				}
			}
			else
			{
				_retries = 1;
				VoodooCrossPromo.Info.HasInternet = true;
				try
				{
					if (string.IsNullOrEmpty(www.downloadHandler.text))
					{
						throw new Exception("JSON Empty");
					}
					VoodooCrossPromo.Info.CurrentGame = JsonUtility.FromJson<GameModel>(www.downloadHandler.text);
				}
				catch (Exception ex)
				{
					VoodooLog.Log(VoodooCrossPromo.TAG, ex.ToString());
					VoodooCrossPromo.Info.CurrentGame = null;
					yield break;
				}
				VoodooCrossPromo.Info.FilterAssets();
			}
		}

		private static IEnumerator DownloadFiles()
		{
			if (VoodooCrossPromo.Info.CurrentGame == null)
			{
				VoodooCrossPromo.Info.FillAssetsListFromCache();
				if (!VoodooCrossPromo.Info.CrossPromoIsReady)
				{
					VoodooCrossPromo.Callback.InitComplete(VoodooCrossPromo.Info.Format);
				}
				yield break;
			}
			CleanCache();
			if (CacheManager.GetAllFilesFromCache().Length != 0 && !VoodooCrossPromo.Info.CrossPromoIsReady)
			{
				VoodooCrossPromo.Callback.InitComplete(VoodooCrossPromo.Info.Format);
			}
			int filesDownloaded = 0;
			List<AssetModel> assets = new List<AssetModel>(VoodooCrossPromo.Info.Assets);
			foreach (AssetModel asset in assets)
			{
				if (filesDownloaded == VoodooCrossPromo.Info.CurrentGame.first_time_videos_in_cache)
				{
					break;
				}
				filesDownloaded++;
				PlayerPrefs.SetString(PlayerPrefsUtils.GetKey(asset.file_path), JsonUtility.ToJson(asset));
				if (!CacheManager.IsFileExist(asset.file_path))
				{
					WWW wwwFile = new WWW(asset.file_url);
					yield return wwwFile;
					if (wwwFile.error == null)
					{
						CacheManager.WriteFile(asset.file_path, wwwFile.bytes);
						if (!VoodooCrossPromo.Info.CrossPromoIsReady)
						{
							VoodooCrossPromo.Callback.InitComplete(VoodooCrossPromo.Info.Format);
						}
					}
					else
					{
						VoodooLog.LogW(VoodooCrossPromo.TAG, "Failed to download file in cache: " + wwwFile.error);
					}
				}
			}
			if (!VoodooCrossPromo.Info.CrossPromoIsReady)
			{
				VoodooCrossPromo.Callback.InitComplete(VoodooCrossPromo.Info.Format);
			}
		}

		private static void CleanCache()
		{
			try
			{
				string[] allFilesFromCache = CacheManager.GetAllFilesFromCache();
				foreach (string text in allFilesFromCache)
				{
					bool flag = false;
					foreach (AssetModel asset in VoodooCrossPromo.Info.Assets)
					{
						if (CacheManager.CompareTwoFilesName(asset.file_path, text))
						{
							flag = true;
						}
					}
					if (!flag)
					{
						CacheManager.DeleteFile(text);
						PlayerPrefs.DeleteKey(PlayerPrefsUtils.GetKey(text));
					}
				}
			}
			catch (Exception ex)
			{
				VoodooLog.LogW(VoodooCrossPromo.TAG, ex.ToString());
			}
		}

		private IEnumerator DownloadNextFiles(int waterfallCount)
		{
			if (VoodooCrossPromo.Info.CurrentGame != null)
			{
				yield return WaitFinishRetreivingInfo();
				int i = 0;
				List<AssetModel> assets = new List<AssetModel>(VoodooCrossPromo.Info.Assets);
				foreach (AssetModel asset in assets.Skip(waterfallCount))
				{
					if (i == VoodooCrossPromo.Info.CurrentGame.buffer_videos)
					{
						break;
					}
					i++;
					if (!CacheManager.IsFileExist(asset.file_path))
					{
						PlayerPrefs.SetString(PlayerPrefsUtils.GetKey(asset.file_path), JsonUtility.ToJson(asset));
						if (!CacheManager.IsFileExist(asset.file_path))
						{
							WWW wwwFile = new WWW(asset.file_url);
							yield return wwwFile;
							if (wwwFile.error == null)
							{
								CacheManager.WriteFile(asset.file_path, wwwFile.bytes);
							}
						}
					}
				}
			}
		}

		private IEnumerator WaitFinishRetreivingInfo()
		{
			while (_retreiveInfo)
			{
				yield return null;
			}
		}

		private IEnumerator Retry()
		{
			if (_retries <= 10)
			{
				float waitInMillisecondes = (float)(Math.Pow(2.0, _retries) * 100.0);
				_retries++;
				yield return new WaitForSeconds(waitInMillisecondes * 0.001f);
				yield return WaitFinishRetreivingInfo();
				GetGameInfoAndDownload();
			}
		}

		public void WaitForFirstFrame(Action action)
		{
			StartCoroutine(StartWaitForFirstFrame(action));
		}

		private static IEnumerator StartWaitForFirstFrame(Action action)
		{
			yield return null;
			if (AFormatManager.Instance == null)
			{
				VoodooLog.LogW(VoodooCrossPromo.TAG, "No prefab found.");
			}
			else
			{
				action();
			}
		}
	}
}
